package com.taotao.utils;

import com.alibaba.fastjson.JSONObject;

import com.taotao.asyn.AsynSendWechatTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

/**
 * 全局捕获异常
 */
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @Value("${server.port}")
    private String serverPort;
    @Value("${spring.application.name}")
    private String serviceName;

    @Autowired
    private AsynSendWechatTemplate asynSendWechatTemplate;

    @ExceptionHandler(value = Exception.class)
    public String exceptionHandler(Exception e) {
        log.error("未知异常！原因是:" + e);
        JSONObject data = new JSONObject();
        data.put("ip", getIpAddress());
        data.put("port", serverPort);
        data.put("serviceName", serviceName);
        StackTraceElement[] stackTrace = e.getStackTrace();
        StackTraceElement stackTraceElement = stackTrace[0];
        String errorMsg = "报错的内容：" + e.getMessage() + ",详细报错的内容：" + stackTraceElement.toString();
        data.put("errorMsg", errorMsg);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = formatter.format(new Date());
        data.put("errorTime", format);
        // 项目经理、开发组长
        data.put("openId", "ommED6cuwHYsgnT5WcamQhf2zJio");
        asynSendWechatTemplate.add(data);
        return "系统出现错误!";
    }

    public static String getIpAddress() {
        String hostAddress = "";
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostAddress = address.getHostAddress();

        } catch (UnknownHostException e) {
        }
        return hostAddress;
    }
}
